package cn.sylinx.hbatis.plugin;

import java.util.List;

import cn.sylinx.hbatis.log.GLog;

public class PluginStarter {
	
	private List<IPlugin>	pluginList	= null;
	
	private Object[]		params		= null;
	
	public PluginStarter() {
		
	}
	
	public PluginStarter(List<IPlugin> pluginList) {
		this.pluginList = pluginList;
	}
	
	public PluginStarter(List<IPlugin> pluginList, Object[] params) {
		this.pluginList = pluginList;
		this.params = params;
	}
	
	public void setPluginList(List<IPlugin> pluginList) {
		this.pluginList = pluginList;
	}
	
	public boolean start() {
		
		if (pluginList != null) {
			
			for (IPlugin plugin : pluginList) {
				try {
					
					boolean success = plugin.start(params);
					if (!success) {
						String message = "Plugin start error: "
								+ plugin.getClass().getName();
						GLog.error(message);
						throw new RuntimeException(message);
					} else {
						
						GLog.info("Plugin[{}] started", plugin.getClass().getName()); 
					}
					
				} catch (Exception e) {
					String message = "Plugin start error: "
							+ plugin.getClass().getName() + ". \n"
							+ e.getMessage();
					GLog.error(message, e);
					throw new RuntimeException(message, e);
				}
			}
		}
		
		return true;
	}
	
	public boolean stop() {
		
		if (pluginList != null) {
			
			for (IPlugin plugin : pluginList) {
				try {
					
					boolean success = plugin.stop();
					if (!success) {
						String message = "Plugin stop error: "
								+ plugin.getClass().getName();
						GLog.error(message);
						throw new RuntimeException(message);
					}
				} catch (Exception e) {
					String message = "Plugin stop error: "
							+ plugin.getClass().getName() + ". \n"
							+ e.getMessage();
					GLog.error(message, e);
					throw new RuntimeException(message, e);
				}
			}
		}
		
		return false;
	}
	
}
